package com.comdo.newup_loan.util;

import android.content.Context;
import android.os.Environment;
import android.view.View;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {

	/**
	 * 判断是否为空
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isNull(String s) {
		if (null == s || s.equals("") || s.equalsIgnoreCase("null")) {
			return true;
		}
		return false;
	}

	public static boolean isFloat(String s) {

		Pattern pattern = Pattern
				.compile("^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*$");
		Matcher matcher = pattern.matcher(s);

		Pattern pattern1 = Pattern.compile("^[1-9]\\d*$");
		Matcher matcher1 = pattern1.matcher(s);
		return matcher.matches() || matcher1.matches();
	}

	/**
	 * 账号加密
	 * 
	 * @param data
	 * 
	 * @return
	 */
	public static String accountEncryption(String data) {
		if(StringUtils.isNull(data))
			return "";
		if (data.length() <= 2) {
			return "****";
		} else {
			StringBuffer sb = new StringBuffer();
			sb.append(data.substring(0, 1)).append("****")
					.append(data.substring(data.length() - 1, data.length()));
			return sb.toString();
		}
	}

	/**
	 * 姓名加密
	 * 
	 * @param data
	 * 
	 * @return
	 */
	public static String NameReplace(String data) {
		if (data.length() < 2) {
			return data;
		} else if (data.length() == 2) {
			return data.substring(0, 1) + "*";
		} else {
			int size = data.length();
			String start = data.substring(0, 1);
			String end = data.substring(size - 1);
			String center = "";
			for (int i = 0; i < size - 2; i++) {
				center = "*" + center;
			}
			return start + center + end;
		}
	}

	/**
	 * 姓名加密(只显示姓-其余 **)
	 * 
	 * @param data
	 * 
	 * @return
	 */
	public static String FristName(String data) {
		if (data == null) {
			return "";
		}
		if (data.length() < 2) {
			return data + "**";
		} else {
			return data.substring(0, 1) + "**";
		}
	}

	/**
	 * 根据索引去数组取值
	 * 
	 * @param dataResource
	 *            数组(配置在strings.xml)
	 * @param index
	 *            索引
	 * @return
	 */
	public static String getStringArrayValueByIndex(String[] dataResource,
			int index) {
		return index > dataResource.length - 1 ? "" : dataResource[index];
	}

	/**
	 * 金额逗号分隔
	 * 
	 * @param
	 * @return
	 */
	public static String calculateMoney(double money) {

		NumberFormat nf = NumberFormat.getInstance();

		return nf.format(money) + "元";
	}

	/**
	 * 计算天数
	 * 
	 * @param days
	 * @return
	 */
	public static String calculateDays(int days) {
		return days < 30 ? days + "天" : days / 30 + "个月";
	}

	/**
	 * 计算天数,没有单位
	 * 
	 * @param days
	 * @return
	 */
	public static String notUnit(int days) {
		return days < 30 ? days + "" : days / 30 + "";
	}

	/**
	 * 计算天数,没有单位
	 * 
	 * @param days
	 * @return
	 */
	public static boolean notUnit_flag(int days) {
		return days < 30 ? true : false;
	}

	/**
	 * 手机号验证
	 * 
	 * @param
	 * @return 验证通过返回true
	 */
	public static boolean isMobile(String str) {

		Pattern p = null;
		Matcher m = null;
		boolean b = false;
		p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
		m = p.matcher(str);
		b = m.matches();
		return b;
	}

	/**
	 * email格式验证
	 * 
	 * @param
	 * @return 验证通过返回true
	 */
	public static boolean checkEmail(String email) {
		Pattern pattern = Pattern
				.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
		Matcher matcher = pattern.matcher(email);
		return matcher.matches();

	}

	/**
	 * 密码格式验证 6-20位字母、数字及组合，区分大小写
	 * 
	 * @param
	 * @return 验证通过返回true
	 */
	public static boolean checkPassWord(String password) {
		Pattern pattern = Pattern.compile("[0-9a-zA-Z]{6,20}");
		Matcher matcher = pattern.matcher(password);
		return matcher.matches();

	}

	/**
	 * 密码格式验证 6-20位字母、数字及组合，区分大小写,必须英文数字混合
	 * 
	 * @param
	 * @return 验证通过返回true
	 */
	public static boolean checkPassWordMix(String password) {
		Pattern pattern = Pattern
				.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$");
		Matcher matcher = pattern.matcher(password);
		return matcher.matches();

	}

	/**
	 * 判断邮编
	 * 
	 * @param
	 * @return
	 */
	public static boolean isZipNO(String zipString) {
		String str = "^[1-9][0-9]{5}$";
		return Pattern.compile(str).matcher(zipString).matches();
	}

	/**
	 * 去除所有空格
	 * 
	 * @param str
	 * @return
	 */
	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}

	public static boolean isIDcard(String str) {

		Pattern p = Pattern
				.compile("^(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)$");
		Matcher m = p.matcher(str);

		return m.matches();
	}

	/**
	 * 使用java正则表达式去掉多余的.与0
	 * 
	 * @param s
	 * @return
	 */
	public static String subZeroAndDot(String s) {
		if (s.indexOf(".") > 0) {
			s = s.replaceAll("0+?$", "");// 去掉多余的0
			s = s.replaceAll("[.]$", "");// 如最后一位是.则去掉
		}
		return s;
	}

	/*
	 * 保留小数点后两位
	 */
	public static String getMoneyString(double money) {
		return String.format("%.2f", money);
	}
	/*
	 * 金额逗号分隔保留两位小数
	 * D -- Decimal 小数
	 * C -- Comma 逗号
	 */
	public static String getMoneyDC(double money) {
		String num = String.format("%.2f", money);
		BigDecimal bd = new BigDecimal(num);
		bd = bd.setScale(2,BigDecimal.ROUND_UP);
		NumberFormat nf=NumberFormat.getInstance(Locale.US);
		return nf.format(bd.doubleValue());
	}

	/*
	 * 保留小数点后一位
	 */
	public static float getMoneyFloat(float money) {
		return Float.parseFloat(String.format("%.1f", money));

	}
	/*
	 * 大于15就显示15（年利率）
	 */
	public static float getyearRateFloat(float yearRate) {
		float lv=Float.parseFloat(String.format("%.1f", yearRate));
		return (float) (lv>15.0?15.0:lv);
	}
	public static float getyearRateFloat1(Double yearRate) {
		float lv=Float.parseFloat(String.format("%.1f", yearRate));
		return (float) (lv>15.0?15.0:lv);
	}
	/*
	 * 进行加法运算
	 */
	public static BigDecimal add(double d1, double d2) {
		BigDecimal b1 = new BigDecimal(d1);
		BigDecimal b2 = new BigDecimal(d2);
		return b1.add(b2);
	}

	/*
	 * 进行乘法运算
	 */
	public static double mul(double d1, double d2) {
		BigDecimal b1 = new BigDecimal(d1);
		BigDecimal b2 = new BigDecimal(d2);
		return b1.multiply(b2).doubleValue();
	}

	/**
	 * 判断SD卡存在
	 * 
	 * @return
	 */
	public static boolean hasSDCard() {
		String status = Environment.getExternalStorageState();
		if (!status.equals(Environment.MEDIA_MOUNTED)) {
			return false;
		}
		return true;
	}


	/**
	 * MD5加密算法
	 * 
	 * @param plainText
	 * @return
	 */
	public static String Md5(String plainText) {
		String md5Password = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
//			plainText.getBytes(Charset.forName("UTF-8"));
			md.update(plainText.getBytes());
			byte b[] = md.digest();

			int i;

			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			md5Password = buf.toString();

			System.out.println("result: " + buf.toString());// 32位的加密
			// System.out.println("result: " + buf.toString().substring(8,
			// 24));// 16位的加密

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return md5Password;
	}

	public static String SortStringAndAddKey(HashMap<String, Object> map) {
		if (map != null && map.keySet() != null && map.keySet().size() > 0) {
			String temp = null;
			String[] s = new String[map.keySet().size()];
			s = map.keySet().toArray(s);
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < map.keySet().size(); i++) {
				for (int j = i + 1; j < map.keySet().size(); j++) {
					if (compare(s[i], s[j]) == false) {
						temp = s[i];
						s[i] = s[j];
						s[j] = temp;
					}
				}
			}
			sb.append("comdosoft");
			for (int i = 0; i < s.length; i++) {
				sb.append(s[i]).append("=").append(map.get(s[i]));
				if (i != s.length - 1) {
					sb.append("&");
				}
			}
			sb.append("comdosoft");
			System.err.println(sb.toString().replaceAll("\\\\", ""));
			return Md5(sb.toString()).toUpperCase();
		}
		return null;
	}

	public static boolean compare(String s1, String s2) {
		boolean result = true;
		for (int i = 0; i < s1.length() && i < s2.length(); i++) {
			if (s1.charAt(i) > s2.charAt(i)) {
				result = false;
				break;
			} else if (s1.charAt(i) < s2.charAt(i)) {
				result = true;
				break;
			} else {
				if (s1.length() < s2.length()) {
					result = true;
				} else {
					result = false;
				}
			}
		}
		return result;

	}

	/**
	 * 身份证号验证
	 * 
	 * @param IDStr
	 * @return
	 */
	public static boolean isIdentityCard(String IDStr) {
		String errorInfo = "";// 记录错误信息
		String[] ValCodeArr = { "1", "0", "x", "9", "8", "7", "6", "5", "4",
				"3", "2" };
		String[] Wi = { "7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7",
				"9", "10", "5", "8", "4", "2" };
		// String[] Checker = {"1","9","8","7","6","5","4","3","2","1","1"};
		String Ai = "";

		// ================ 号码的长度 15位或18位 ================
		if (IDStr.length() != 15 && IDStr.length() != 18) {
			errorInfo = "号码长度应该为15位或18位。";
			System.out.println(errorInfo);
			return false;
		}
		// =======================(end)========================

		// ================ 数字 除最后以为都为数字 ================
		if (IDStr.length() == 18) {
			Ai = IDStr.substring(0, 17);
		} else if (IDStr.length() == 15) {
			Ai = IDStr.substring(0, 6) + "19" + IDStr.substring(6, 15);
		}
		if (isNumeric(Ai) == false) {
			errorInfo = "15位号码都应为数字 ; 18位号码除最后一位外，都应为数字。";
			System.out.println(errorInfo);
			return false;
		}
		// =======================(end)========================

		// ================ 出生年月是否有效 ================
		String strYear = Ai.substring(6, 10);// 年份
		String strMonth = Ai.substring(10, 12);// 月份
		String strDay = Ai.substring(12, 14);// 月份

		if (isDate(strYear + "-" + strMonth + "-" + strDay) == false) {
			errorInfo = "生日无效。";
			System.out.println(errorInfo);
			return false;
		}

		GregorianCalendar gc = new GregorianCalendar();
		SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
		try {
			if ((gc.get(Calendar.YEAR) - Integer.parseInt(strYear)) > 150
					|| (gc.getTime().getTime() - s.parse(
							strYear + "-" + strMonth + "-" + strDay).getTime()) < 0) {
				errorInfo = "生日不在有效范围。";
				System.out.println(errorInfo);
				return false;
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if (Integer.parseInt(strMonth) > 12 || Integer.parseInt(strMonth) == 0) {
			errorInfo = "月份无效";
			System.out.println(errorInfo);
			return false;
		}
		if (Integer.parseInt(strDay) > 31 || Integer.parseInt(strDay) == 0) {
			errorInfo = "日期无效";
			System.out.println(errorInfo);
			return false;
		}
		// =====================(end)=====================

		// ================ 地区码时候有效 ================
		Hashtable h = GetAreaCode();
		if (h.get(Ai.substring(0, 2)) == null) {
			errorInfo = "地区编码错误。";
			System.out.println(errorInfo);
			return false;
		}
		// ==============================================

		// ================ 判断最后一位的值 ================
		int TotalmulAiWi = 0;
		for (int i = 0; i < 17; i++) {
			TotalmulAiWi = TotalmulAiWi
					+ Integer.parseInt(String.valueOf(Ai.charAt(i)))
					* Integer.parseInt(Wi[i]);
		}
		int modValue = TotalmulAiWi % 11;
		String strVerifyCode = ValCodeArr[modValue];
		Ai = Ai + strVerifyCode;

		if (IDStr.length() == 18) {
			if (Ai.equals(IDStr) == false) {
				errorInfo = "身份证无效，最后一位字母错误";
				System.out.println(errorInfo);
				return false;
			}
		} else {
			System.out.println("所在地区:" + h.get(Ai.substring(0, 2).toString()));
			System.out.println("新身份证号:" + Ai);
			return true;
		}
		// =====================(end)=====================
		System.out.println("所在地区:" + h.get(Ai.substring(0, 2).toString()));
		return true;

	}

	private static boolean isDate(String strDate) {
		Pattern pattern = Pattern
				.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))"
						+ "[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?"
						+ "((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))"
						+ "[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|"
						+ "(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|"
						+ "(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
		Matcher m = pattern.matcher(strDate);

		return m.matches();

	}

	private static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);

		return isNum.matches();
	}

	private static Hashtable GetAreaCode() {
		Hashtable hashtable = new Hashtable();
		hashtable.put("11", "北京");
		hashtable.put("12", "天津");
		hashtable.put("13", "河北");
		hashtable.put("14", "山西");
		hashtable.put("15", "内蒙古");
		hashtable.put("21", "辽宁");
		hashtable.put("22", "吉林");
		hashtable.put("23", "黑龙江");
		hashtable.put("31", "上海");
		hashtable.put("32", "江苏");
		hashtable.put("33", "浙江");
		hashtable.put("34", "安徽");
		hashtable.put("35", "福建");
		hashtable.put("36", "江西");
		hashtable.put("37", "山东");
		hashtable.put("41", "河南");
		hashtable.put("42", "湖北");
		hashtable.put("43", "湖南");
		hashtable.put("44", "广东");
		hashtable.put("45", "广西");
		hashtable.put("46", "海南");
		hashtable.put("50", "重庆");
		hashtable.put("51", "四川");
		hashtable.put("52", "贵州");
		hashtable.put("53", "云南");
		hashtable.put("54", "西藏");
		hashtable.put("61", "陕西");
		hashtable.put("62", "甘肃");
		hashtable.put("63", "青海");
		hashtable.put("64", "宁夏");
		hashtable.put("65", "新疆");
		hashtable.put("71", "台湾");
		hashtable.put("81", "香港");
		hashtable.put("82", "澳门");
		hashtable.put("91", "国外");
		return hashtable;
	}

	/**
	 * Measure the view
	 * 
	 * @param view
	 */
	public static void calcViewMeasure(View view) {
		int width = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		int expandSpec = View.MeasureSpec.makeMeasureSpec(
				Integer.MAX_VALUE >> 2, View.MeasureSpec.AT_MOST);
		view.measure(width, expandSpec);
	}

	/**
	 * Translate the <i>dip</i> to <i>px</i>
	 * 
	 * @param context
	 * @param dpValue
	 * @return
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/*
	 * 银行卡打星号
	 */
	public static String BankReplace(String bankNum) {
		if (bankNum != null) {
			int size = bankNum.length();
			if (size > 8) {
				String start = bankNum.substring(0, 4);
				String end = bankNum.substring(size - 4);
				String center = "";
				for (int i = 0; i < size - 8; i++) {
					center = "*" + center;
				}

				return start + center + end;
			} else {
				return bankNum;
			}
		} else {
			return bankNum;
		}
	}
}
